package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AdminFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获得请求路径
        String path = request.getURI().getPath();
        /*
            判断是否要鉴权  查看请求路径中是否含有/login
         */
        if (path.contains("/login")){
            //有则路由到微服务
            return chain.filter(exchange);
        }

        /*
            没有则判断是否有token
         */
        String token = request.getHeaders().getFirst("token");
        //有token则路由到微服务
        if (!StringUtils.isEmpty(token)){
            //解析token 解析成功
            try {
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                //判断token是否有效
                int status = AppJwtUtil.verifyToken(claimsBody);
                if (status == -1 || status ==0){
                    //token有效则将token中的信息放入到请求头中
                    Object userId = claimsBody.get("userId");
                    request.mutate().header("userId",userId.toString());

                    //转发到微服务中
                    return chain.filter(exchange);
                }
                //解析失败
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        //没有token或者token无效则返回401错误提示
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 执行的顺序  数字越小  执行越早
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
